package com.hoperun.checkcloth.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hadilq.liveevent.LiveEvent
import com.hoperun.checkcloth.R
import com.hoperun.checkcloth.repository.Repository
import kotlinx.coroutines.launch

class LeftOverBoltLoginViewModel : ViewModel() {

    // 信息提示
    private val _dialogMessage = LiveEvent<Int>()
    val dialogMessage: LiveData<Int> = _dialogMessage

    // 导航事件
    private val _navigation = LiveEvent<String>()
    val navigation: LiveData<String> = _navigation

    // 加载动画
    private val _loading = LiveEvent<Boolean>()
    val loading: LiveData<Boolean> = _loading

    /***
     * 登录请求
     *
     */
    fun login(account: String, password: String) = viewModelScope.launch {
        _loading.value = true
        launch inner@{
            if (account.isEmpty()) {
                _dialogMessage.value = R.string.login_error_account_empty
                return@inner
            }

            if (password.isEmpty()) {
                _dialogMessage.value = R.string.login_error_password_empty
                return@inner
            }

            if (Repository.accountPasswordLogin(account, password)) {
                _navigation.value = "jump to LeftOverBoltMain"
            } else {
                _dialogMessage.value = R.string.login_error_wrong_account_password
            }
        }.invokeOnCompletion { _loading.value = false }
    }

}